package com.ywjh.inter.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.ywjh.inter.common.MemKey;
import com.ywjh.inter.conn.DBConnection;
import com.ywjh.inter.conn.MemcacheConn;
import com.ywjh.inter.dao.BGluRangeDAO;
import com.ywjh.inter.entity.BGluRangeEntity;

import net.sf.json.JSONObject;

public class SettingService {
	private static SettingService settingServer;
	private BGluRangeDAO bGluRangeDAO;

	public static SettingService getInstance() {
		if (settingServer == null) {
			settingServer = new SettingService();
			settingServer.bGluRangeDAO = new BGluRangeDAO();
		}
		return settingServer;
	}

	public boolean setBgluRange(List<BGluRangeEntity> list, int userId) {
		boolean b = false;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			if (bGluRangeDAO.findByUserId(conn, userId) != null) {
				b = bGluRangeDAO.delete(conn, userId);
			}
			b = bGluRangeDAO.insert(conn, list);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return b;
	}

	public Map<Integer, BGluRangeEntity> getBgluRange(int user_id) {
		Map<Integer, BGluRangeEntity> map = null;
		Connection conn = null;
		try {
			conn = DBConnection.getDBConnection();
			map = bGluRangeDAO.findByUserId(conn, user_id);
			if (map == null || map.isEmpty()) {
				map = bGluRangeDAO.findByUserId(conn, -1);
				System.out.println("未找到用户配置，使用默认");
			}else {
				System.out.println("找到用户配置");
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			DBConnection.close(conn);
		}
		return map;
	}

	public JSONObject getAppDoc() {
		try {
			JSONObject json = JSONObject.fromObject(MemcacheConn.getInstance().get(MemKey.APP_DOC));
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public JSONObject getAppPatient() {
		try {
			JSONObject json = JSONObject.fromObject(MemcacheConn.getInstance().get(MemKey.APP_PATIENT));
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
